﻿using Coldairarrow.Entity.Base_leasesystem_merchant;
using Coldairarrow.Entity.Base_leasesystem_service;
using Coldairarrow.Entity.Base_leasesystem_serviceaccount;
using Coldairarrow.Entity.Base_leasesystem_servicebank;
using Coldairarrow.Entity.Base_leasesystem_servicesign;
using Coldairarrow.Entity.Base_leasesystem_signfile;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Base_leasesystem_servicesign
{
    public class leasesystem_servicesignBusiness : BaseBusiness<leasesystem_servicesign>, Ileasesystem_servicesignBusiness, ITransientDependency
    {
        public leasesystem_servicesignBusiness(IDbAccessor db)
            : base(db)
        {
        }

        #region 外部接口

        public async Task<object> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            //var q = GetIQueryable();
            //var where = LinqHelper.True<leasesystem_servicesign>();
            //var search = input.Search;

            ////筛选
            //if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            //{
            //    var newWhere = DynamicExpressionParser.ParseLambda<leasesystem_servicesign, bool>(
            //        ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
            //    where = where.And(newWhere);
            //}

            //return await q.Where(where).GetPageResultAsync(input);

            var obj = Db.GetIQueryable<leasesystem_servicesign>()
                .Join(Db.GetIQueryable<leasesystem_merchant>(), a => a.MID, b => b.Id, (a, b) => new
                {
                    b.customerName,
                    a.BeginDate,
                    a.EndDate,
                    a.Rate,
                    a.UseStatus,
                });
            
            var newwhere = obj.Where(a => a.customerName.Contains(input.Search.Keyword));

            var result = new {
                Data = newwhere.Skip((input.PageIndex - 1) * input.PageRows)
                .Take(input.PageRows)
                .ToListAsync(),
                Total = obj.Count()
        };
            return result; 
        }

        public async Task<leasesystem_servicesign> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        public async Task AddDataAsync(leasesystem_servicesign data)
        {
            var servicesing = Db.GetIQueryable<leasesystem_servicesign>().Where(a => a.ServiceId == data.ServiceId && a.MID == data.MID);
            if (servicesing.Count() < 1)
            {
                await InsertAsync(data);
            }
            else {
                throw new BusException("该客户与该服务器已签约!");
            }
            
        }

        public async Task UpdateDataAsync(leasesystem_servicesign data)
        {
            await UpdateAsync(data);
        }

        public async Task DeleteDataAsync(List<string> ids)
        {
            for (int i = 0; i < ids.Count; i++)
            {
                var Msign = Db.GetEntity<leasesystem_servicesign>(ids[i]);
                var MFile =await Db.GetIQueryable<leasesystem_signfile>().Where(a => a.Rid == Msign.FileAttId).ToListAsync();
                //MFile.ForEach(a => {   DeleteAsync(a.Id); });
                for (int k = 0; k < MFile.Count(); k++)
                {
                  await  Db.DeleteAsync<leasesystem_signfile>(MFile[k].Id);
                }
            }
            await DeleteAsync(ids);
        }

        public IQueryable GetAll(PageInput<ConditionDTO> input)
        {
            var list = from chant in Db.GetIQueryable<leasesystem_servicesign>()
                       join mer_img in Db.GetIQueryable<leasesystem_merchant>()
                       on chant.MID equals mer_img.Id into temp
                       from tempT in temp.DefaultIfEmpty()
                       select new
                       {
                           Id = chant.Id,
                           createTime = chant.CreateTime,
                           creatorId = chant.CreatorId,
                           customerName = tempT.customerName,
                           BeginDate = chant.BeginDate.ToString(),
                           EndDate = chant.EndDate.ToString(),
                           Rate = chant.Rate,
                           UseStatus = chant.UseStatus

                       };
            return list.GetPageAll(input);
        }

        public async Task<object> GetService_BankByMID(string id) 
        {
            var query = Db.GetIQueryable<leasesystem_servicesign>().Where(a => a.MID == id);

            if (query.Count() > 0)
            {
                var serviceinfo = await Db.GetIQueryable<leasesystem_service>()
                    .Where(a => a.Id == query.FirstOrDefault().ServiceId).Select(a => new
                    {
                        a.Id,
                        a.ServiceName
                    }).ToListAsync();
                var servicebank = await Db.GetIQueryable<leasesystem_serviceaccount>()
                    .Where(a => a.SID == query.FirstOrDefault().ServiceId).Select(a => new
                    {
                        a.Id,
                        a.BankName,
                        a.AcctNo
                    }).ToListAsync();
                var result = new
                {
                    serviceRate = query.FirstOrDefault().Rate,
                    serviceinfo = serviceinfo,
                    servicebank = servicebank
                };
                return result;
            }
            else {
                throw new BusException("该客户未完成签约！");
            }
        }

        #endregion

        #region 私有成员

        #endregion
    }
}